package com.hutao.manage.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hutao.manage.util.thread.PdfRenderThread;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFUtil {
	private static Logger log = LoggerFactory.getLogger(PDFUtil.class);
	
	/**
	 * 合并pdf文件
	 * 
	 * @param files
	 * @param savepath
	 */
	public static void mergePdfFiles(String[] files, String savepath) throws Exception{
		Document document = null;
		OutputStream outPutStream = null;
		PdfCopy copy = null;
		PdfReader pdfReader = null;
		
		try {
			pdfReader = new PdfReader(files[0]);
			document = new Document(pdfReader.getPageSize(1));
			document.setPageSize(PageSize.A4);
			outPutStream = new FileOutputStream(savepath);
			copy = new PdfCopy(document, outPutStream);
			document.open();
			for (int i = 0; i < files.length; i++) {
					PdfReader reader = new PdfReader(files[i]);
					
					try {
						int n = reader.getNumberOfPages();
						for (int j = 1; j <= n; j++) {
							document.newPage();
							PdfImportedPage page = copy.getImportedPage(reader, j);
							copy.addPage(page);
						}
						
					}  finally {
						if (reader != null) {
							reader.close();
						}
					}
			
			}
		} finally {
			if (null != copy) {
				copy.close();
			}
			
			if (pdfReader != null) {
				pdfReader.close();
			}
			
			if (null != document) {
				document.close();
			}
			if (null != outPutStream) {
				outPutStream.close();
			}
		}
	}
	
	
	
	/**
	 * 图片转PDF
	 * @param imgFileNameArr
	 * 
	 * @param pdfFilePath
	 * @return
	 * @throws Exception
	 */
	public static String Img2PDF(List<String> imgFileNameArr,String pdfFilePath) throws Exception {
		OutputStream out = new FileOutputStream(new File(pdfFilePath));
		Document document = new Document(null,0,0,0,0);
		document.setPageSize(PageSize.A4);
		PdfWriter.getInstance(document, out);
		document.open();
		for (String path : imgFileNameArr) {
			Image image = Image.getInstance(path);
			float imageHeight = image.getScaledHeight();
			float imageWidth = image.getScaledWidth();
			int i = 0;
			while (imageHeight > PageSize.A4.getHeight() || imageWidth > PageSize.A4.getWidth()) {
				image.scalePercent(100 - i);
				i++;
				imageHeight = image.getScaledHeight();
				imageWidth = image.getScaledWidth();
			}
			image.setAlignment(Image.ALIGN_CENTER);
			
			// 插入一个图片
			document.add(image);
			
		}
		
		document.close();
		out.close();
		return pdfFilePath;
	}
	
	
	/**
	 * PDF转为图片
	 * @param pdfPath
	 * 				pdf路径
	 * @param imagePath
	 * 				文件存放路径
	 * @return
	 * 				图片名称集合
	 */
	public static List<String> pdf2Img(String pdfPath,String imagePath){
		List<String> imageList = new LinkedList<String>();
		File file = new File(pdfPath);
		BufferedImage image = null;
		PDDocument doc = null;
		PDFRenderer render = null;
		
		try {
			doc = PDDocument.load(file);
			render = new PDFRenderer(doc);
			int pageCount = doc.getNumberOfPages();
			for(int i=0;i<pageCount;i++) {
				image = render.renderImageWithDPI(i,197f);
				String fileName = StringUtil.getFileName()+".png";
				ImageIO.write(image, "png", new File(imagePath+fileName));
				imageList.add(fileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(doc!=null)doc.close();
				if(image!=null) {
					image=null;
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
		return imageList;
		
	}
	
	public static List<String> pdf2Img1(String pdfPath, final String imagePath) throws Exception{
		List<String> imageList = new LinkedList<String>();
		File file = new File(pdfPath);
		PDDocument doc = null;
		PDFRenderer render = null;
		
		try {
			doc = PDDocument.load(file);
			render = new PDFRenderer(doc);
			int pageCount = doc.getNumberOfPages();
			int pageSize = 4;
			int maxThreadNum = 10;
			if (pageCount > 40) {
				pageSize = pageCount/maxThreadNum;
			}
			
			int threadNumber = 0;
			if (pageCount % pageSize != 0) {
				threadNumber = pageCount/pageSize + 1;
			} else {
				threadNumber = pageCount/pageSize;
			}
			
			CountDownLatch latch = new CountDownLatch(threadNumber);
			List<Integer> pageList = new ArrayList<Integer>();
			List<String> fileNameList = new ArrayList<String>();
			int threadCount = 0;
			
			for (int i = 0; i < pageCount; i++) {
				String fileName =  StringUtil.getId() + ".jpg";
				imageList.add(fileName);
				fileNameList.add(fileName);
				pageList.add(i);
				if ((i+1) % pageSize == 0) {
					PdfRenderThread pdfRenderThread = new PdfRenderThread(render, pageList,
							fileNameList, imagePath, pdfPath ,latch);
					threadCount++;
					new Thread(pdfRenderThread).start();
					pageList = new ArrayList<Integer>();
					fileNameList = new ArrayList<String>();
				}
			}
			
			if (pageList.size() > 0) {
				PdfRenderThread pdfRenderThread = new PdfRenderThread(render, pageList, fileNameList, imagePath, pdfPath, latch);
				new Thread(pdfRenderThread).start();
				threadCount++;
			}
			System.out.println("threadCount = " + threadCount );
			latch.await();
		}  finally {
			try {
				if (doc != null)
					doc.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

		return imageList;
	}
	
	/**
	 * @param pages
	 * @param pdffile
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static void mergePdf(File[] pages, File pdffile) throws Exception,
			DocumentException {
		if (!pdffile.exists()) {
			pdffile.createNewFile();
		}
		if (pages.length < 1)
			return;

		Document document = new Document(new PdfReader(
				((File) pages[0]).getAbsolutePath()).getPageSize(1));
		PdfCopy copy = new PdfCopy(document, new FileOutputStream(pdffile));
		document.open();
		for (int i = 0; i < pages.length; i++) {
			PdfReader reader = new PdfReader((pages[i]).getAbsolutePath());
			int num = reader.getNumberOfPages();
			for (int j = 1; j <= num; j++) {
				document.newPage();
				PdfImportedPage page = copy.getImportedPage(reader, j);
				copy.addPage(page);
			}
		}
		document.close();
		//删除文件
		for (File page : pages) {
		 page.deleteOnExit();
		}
	}
	
	
	/**
	 * 生成放射科检查pdf
	 * 
	 * @param map
	 * @param homePageTemplatePDFPath
	 * @param targetPath
	 */
	public static void getNrs2000ByTemplate(Map<String, Object> map, String homePageTemplatePDFPath,
			String targetPath) throws Exception{
		PdfReader reader = null;
		OutputStream bos = null;
		PdfStamper stamper = null;
		try {
			reader = new PdfReader(homePageTemplatePDFPath);// 读取pdf模板
			bos = new FileOutputStream(new File(targetPath));
			stamper = new PdfStamper(reader, bos);
			AcroFields form = stamper.getAcroFields();
			// 使用中文字体
			BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
			fontList.add(bf);
			form.setSubstitutionFonts(fontList);
			form.setField("name", "张三");
			form.setField("onlyId","1-1000000");
			form.setField("sex", "男");	
			form.setField("deptName","骨科一病房");
			form.setField("bedNo", "一床");
			form.setField("heighh", "1.8");
			form.setField("weight", "74");
			form.setField("bmi","24.5");
			form.setField("protein", "10.2");
			form.setField("diagnosis", "感冒");
			form.setField("disease1", "√");
			form.setField("nutritional0", "√");
			form.setField("ageScore","√");
			form.setField("total2","√");
			form.setField("raIdCard", "张凯");
			form.setField("raTime", "2020-09-01 12:23:12");

			/*
			 * if(map.get("radioImgs")!=null && map.get("radioImgs")!="") { String radioImgs
			 * = (String)map.get("radioImgs"); String [] imgs = radioImgs.split(","); for
			 * (int i = 0; i < imgs.length; i++) { if(i>1) { continue; } int pageNo
			 * =form.getFieldPositions("image"+i).get(0).page; Rectangle signRect
			 * =form.getFieldPositions("image"+i).get(0).position; float x =
			 * signRect.getLeft(); float y =signRect.getBottom();
			 * 
			 * Image image = Image.getInstance(imgs[i]); // 获取操作的页面 PdfContentByte under
			 * =stamper.getOverContent(pageNo); // 根据域的大小缩放图片
			 * image.scaleToFit(signRect.getWidth(),signRect.getHeight()); // 添加图片
			 * image.setAbsolutePosition(x, y); under.addImage(image);
			 * 
			 * } }
			 */
			stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true

		}  finally {
			if (stamper != null) {
				stamper.close();
			}
			
			if (reader != null) {
				try {
					reader.close();
				} catch (Exception e2) {
				}
			}
			
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
	
	
	
	public static void main(String[] args) throws Exception {
		/*
		 * List<String> list = pdf2Img("D://MrDoc/sy/首页山东省立医院-6517837-20191030(2).PDF",
		 * "D://MrDoc/sy/");
		 * 
		 * List<String> list1 = new LinkedList<>(); for (String string : list) {
		 * System.out.println(string);
		 * 
		 * 
		 * list1.add("D://MrDoc/sy/"+string); }
		 * 
		 * Img2PDF(list1, "D://MrDoc/sy/10845441.pdf");
		 */
		String [] arr = {"D://1.png","D://2.png"};
		Img2PDF(Arrays.asList(arr),"D://111.pdf");
		
	}
	
	

}
